package com.fr.lintcode;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
*作者：furong
*日期：2017年1月19日
*时间：下午6:15:33
*/
public class Q120 {
    /**
     * @param start, a string
     * @param end, a string
     * @param dict, a set of string
     * @return an integer
     */
    public int ladderLength(String start, String end, Set<String> dict) {
        if (start == null || end == null) {
            return 0;
        }
        if (start.equals(end)) {
            return 1;
        }
        if (check(start, end)) {
            return 2;
        }
        if (dict == null || dict.size() <= 0) {
            return 0;
        }
        ArrayList<String> ds = new ArrayList<>(dict);
        int length = dict.size();
        List<Integer> begin = new ArrayList<>();
        List<Integer> reach = new ArrayList<>();
        List<Integer> left = new ArrayList<>(length);
        int count = 1;
        boolean a[][] = new boolean[length][length];
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length; j++) {
                if (i == j) {
                    continue;
                } else if (i > j) {
                    a[i][j] = a[j][i];
                } else {
                    a[i][j] = check(ds.get(i), ds.get(j));
                }
            }
            if (check(start, ds.get(i))) {
                begin.add(i);
            }
            if (check(end, ds.get(i))) {
                reach.add(i);
            }
            left.add(i);
        }
        boolean reachEnd = false;
        while (left.size() > 0 && !reachEnd) {
            left.removeAll(begin);
            List<Integer> tmp = new ArrayList<>();
            if (begin.size() > 0) {
                for (int i : begin) {
                    if (reach.contains(i)) {
                        reachEnd = true;
                        break;
                    }
                    for (int j : left) {
                        if (a[i][j]) {
                            tmp.add(j);
                        }
                    }
                }
                begin = tmp;
                count++;
            } else {
                break;
            }
        }
        if (reachEnd) {
            return count + 1;
        } else {
            return 0;
        }
    }

    private boolean check(String start, String end) {
        int length = start.length();
        int count = 0;
        for (int i = 0; i < length; i++) {
            if (start.charAt(i) != end.charAt(i)) {
                count++;
            }
            if (count >= 2) {
                return false;
            }
        }
        return true;
    }
}
